package com.zaoke.web.dao.food.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;

import com.zaoke.web.bo.food.Nutrition;
import com.zaoke.web.dao.JdbcSupport;
import com.zaoke.web.dao.food.NutritionDao;

public class NutritionDaoImpl extends JdbcSupport implements NutritionDao{

	private static final String TABLE = "`zaoke`.`nutrition`";
	
	@Override
	public Nutrition findNutritionById(long id) {
		
		String sql = "select * from "+TABLE;
		sql +=" where id=?";
		Object[] params = new Object[]{id};
		
		Nutrition res = getTemplateMgr().getReadTp().queryForObject(sql, new RowMapper<Nutrition>() {

			@Override
			public Nutrition mapRow(ResultSet rs, int rowNum)
					throws SQLException {

				Nutrition nu = new Nutrition();
				
				nu.setId(rs.getLong("id"));
				nu.setName(rs.getString("name"));
				nu.setAddTime(rs.getDate("add_time"));
				nu.setAddUserid(rs.getLong("add_userid"));
				nu.setLastmodTime(rs.getDate("lastmod_time"));
				nu.setLastmodUserid(rs.getLong("lastmod_userid"));
				return nu;
			}
		},params);
		
		return res;
	}

	@Override
	public Nutrition findNutritionByName(String name) {
		String sql = "select * from "+TABLE;
		sql +=" where name=?";
		Object[] params = new Object[]{name};
		
		List<Nutrition> res = getTemplateMgr().getReadTp().query(sql, new RowMapper<Nutrition>() {

			@Override
			public Nutrition mapRow(ResultSet rs, int rowNum)
					throws SQLException {

				Nutrition nu = new Nutrition();
				
				nu.setId(rs.getLong("id"));
				nu.setName(rs.getString("name"));
				nu.setAddTime(rs.getDate("add_time"));
				nu.setAddUserid(rs.getLong("add_userid"));
				nu.setLastmodTime(rs.getDate("lastmod_time"));
				nu.setLastmodUserid(rs.getLong("lastmod_userid"));
				return nu;
			}
		},params);
		
		if(res!=null && res.size()>0)
			return res.get(0);
		
		return null;
	}

}
